package server;
/*
 * PackageName: server
 * ClassName:   MyClassLoader
 * Author:   zhang
 * Date:     Created in 2020/11/11
 * Description:
 * History:
 * <author>        <time>             <version>          <desc>
 * 作者姓名         修改时间            版本号              描述
 * zhang           2020/11/11      1.0
 */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * Title:
 * Project: demo1
 *
 * @author ZhangKe
 * Created on 2020/11/11
 */
public class MyClassLoader extends ClassLoader{
    /**
     * 指定路径
     */
    private String path;


    public MyClassLoader(String classPath) {
        path = classPath;
    }

    /**
     * @param name class文件全路径
     * @return
     */
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {

        Class clazz;
        // 获取该class文件字节码数组
        try {
            byte[] clazzByte = this.getByteArray();

            if (clazzByte != null) {
                // 调用defineClass（clazz全路径，clazz的内容数组，offset，length）将class的字节码数组转换成Class类的实例
                clazz = defineClass(name, clazzByte, 0, clazzByte.length);
                return clazz;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //自定义的加载器没有加载到需要的class，那么使用系统类加载器去加载
        return MyClassLoader.getSystemClassLoader().loadClass(name);
    }

    /**
     * 将class文件转化为字节码数组
     *
     * @return byte
     */
    private byte[] getByteArray() throws Exception {

        if (path.length() > 0) {
            File file = new File(path);
            // 内存输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int size = 0;
            while ((size = in.read(buffer)) != -1) {
                out.write(buffer, 0, size);
            }
            return out.toByteArray();
        }
        return null;
    }

}
